package com.jdcjk.chat;

import android.os.Environment;
import android.util.Log;

import com.amap.api.maps.model.LatLng;
import com.google.gson.Gson;
import com.jdcjk.MainApp;
import com.jdcjk.chat.enity.MessageBean;
import com.jdcjk.project.main.model.entity.CarWarningInfo;
import com.jdcjk.util.PreferencesUtils;
import com.jdcjk.util.TimeUtils;

import org.greenrobot.eventbus.EventBus;
import org.jivesoftware.smack.chat.Chat;
import org.jivesoftware.smack.chat.ChatMessageListener;
import org.jivesoftware.smack.packet.Message;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;


/**
 * Created by dong on 2016/7/11.
 * 即时通信聊天监听器
 */
public class OpenFireChatMessageListener implements ChatMessageListener {
    //位置
    private final String LOCATION = "location";
    //终端信息
    private final String TERMINAL_STATUS = "terminalStatus";
    //报警信息
    private final String WARNING = "warning";

    public static final String terminalClose = "terminalClose";
    public static final String updataWarningInfoNumber = "updataWarningInfoNumber";
    private Map<String, String> termianlUpdataTimeMap;
    private String lastGetDataTime;

    @Override
    public void processMessage(Chat chat, Message message) {
        if (message.getBody() != null) {
            //判断时间监听器是否启动，没有则启动
            if (timer != null) {
                //三十分钟一次判断一次
                timer.schedule(new timeTask(), 30 * 60 * 1000L);
            }
            Gson gson = new Gson();
            System.out.println("在线消息：" + message.getBody());
            MessageBean messageBean = gson.fromJson(message.getBody(), MessageBean.class);
            //判断消息类型
            switch (messageBean.getMsgType()) {
                case WARNING:
                    //如果为报警信息
                    CarWarningInfo carWarningInfo = messageBean.getWarming();
                    //获得积累的未阅读的所有报警信息数量
                    int warningNumber = PreferencesUtils.getInt(MainApp.getInstance(), PreferencesUtils.WARNING_INFO_NUMBER);
                    //所有设备报警信息数+1;
                    warningNumber += 1;
                    //存储所有设备未查看报警信息数量
                    PreferencesUtils.setInt(MainApp.getInstance(), PreferencesUtils.WARNING_INFO_NUMBER, warningNumber);
                    //获得对应设备的的未阅读的所有报警信息数量
                    int carWarningNumber = PreferencesUtils.getInt(MainApp.getInstance(), PreferencesUtils.WARNING_INFO_NUMBER + carWarningInfo.getTerminalId());
                    carWarningNumber += 1;
                    //存储对应设备未查看报警信息数量
                    PreferencesUtils.setInt(MainApp.getInstance(), PreferencesUtils.WARNING_INFO_NUMBER + carWarningInfo.getTerminalId(), carWarningNumber);
                    //记录通信时间
                    lastGetDataTime = carWarningInfo.getUpdateTime();
                    //发送更新对应设备报警信息数量的广播
                    EventBus.getDefault().post(updataWarningInfoNumber + String.valueOf(carWarningInfo.getTerminalId()));
                    //判断用户是否开启信息推送
                    if (!PreferencesUtils.getBoolean(MainApp.getInstance(), PreferencesUtils.PUSH_INFO_SWITCH)) {
                        return;
                    }
                    MainApp.getInstance().getWarningByEventBus(carWarningInfo);
                    break;
                case LOCATION:
                    //如果为坐标信息
                    MessageBean.LocationBean locationBean = messageBean.getLocation();
                    LatLng latLng = new LatLng(messageBean.getLocation().getLatitude(), messageBean.getLocation().getLongitude(), true);
                    locationBean.setLatLng(latLng.latitude, latLng.longitude);
                    EventBus.getDefault().post(locationBean);
                    Log.i("OpenFire", "坐标：processMessage:latitude " + latLng.latitude);
                    Log.i("OpenFire", "坐标：processMessage:longitude " + latLng.longitude);
//                    //记录openfire返回数据到文件中
//                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//                        //获得时间当前天数
//                        String time = TimeUtils.getTime(TimeUtils.getCurrentTimeInLong(), TimeUtils.DATE_FORMAT_DATE);
//                        String fileName = "jdcjk-" + time + ".log";
//                        writeFileToSD(fileName, locationBean.getUpdateTime());
//                    }
                    //记录通信时间
                    lastGetDataTime = locationBean.getUpdateTime();
                    break;
                case TERMINAL_STATUS:
                    //如果为终端信息
                    MessageBean.TerminalStatusBean terminalStatusBean = messageBean.getTerminalStatus();
                    EventBus.getDefault().post(terminalStatusBean);
                    //记录通信时间
                    lastGetDataTime = terminalStatusBean.getUpdatedTime();
                    break;
            }

        }
    }


    private void writeFileToSD(String fileName, String message) {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
            return;
        }
        try {
            String pathName = "/sdcard/jdcjk/";
            File path = new File(pathName);
            File file = new File(pathName + fileName);
            if (!path.exists()) {
                path.mkdir();
            }
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream stream = new FileOutputStream(file, true);
            byte[] buf = message.getBytes();
            stream.write(buf);
            stream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Timer timer = null;
    private int waiting = 0;


    class timeTask extends TimerTask {
        @Override
        public void run() {
            //当前时间
            String nowTime = TimeUtils.getCurrentTimeInString();
            //判断上次获得信息与当前时间差值
            if (TimeUtils.calculatingTimeDifferenceValue(nowTime, lastGetDataTime) > 30) {
                //如果超过三十分钟未接收到数据，则判断设备已经关闭，发送设备关闭指令，更新界面显示
                String message = terminalClose;
                EventBus.getDefault().post(message);
            }
            //一分钟一次判断一次
            timer.schedule(new timeTask(), 1 * 60 * 1000L);
        }
    }

}
